#!/usr/bin/env python
# -*- coding: utf-8 -*-
import json

from flask import jsonify, request
from flask_restful import Resource
from utility.odoo_manager import OdooManager  # 操作odoo的单例
from utility.error_code import error_code  # 异常代码
from utility.message_manager import MessageBusManager
from event import event_type
from datetime import datetime, timedelta
from command import command
from utility import tools
from command.handler import dict_handler
import logging
from utility import his_api
# from model.ArchivesModel import ArchivesModel
# from model.LogModel import LogModel
# from model.PhysicalModel import PhysicalModel
# from utility.pgsql_manager import PgSqlManager
FORMAT = "%(asctime)s %(thread)d %(message)s"
logging.basicConfig(level=logging.INFO, format=FORMAT)


class ArchivesSelectPeopleCountAPI(Resource):
    """
    查询建档统计信息
    :request: get
    :returns: json string
    """
    #@AppSecurity.public_verify()
    #@AppSecurity.token_verify()
    def get(self):

        try:
            #  参数校验
            params = request.values
            odoo = OdooManager().get_instance()
            #  建档总人数
            register_num_ = odoo.env['res.archives'].search_count([])
            #  今日建档人数
            today_people_num_ = odoo.env['res.archives'].search_count([
                   ('jd_date', '>=', datetime.strftime(datetime.today(), "%Y-%m-%d"))
                ])
            #  今日挂号人数
            today_gh_num_  = 0
            #  本周产检人次
            sunday, monday = tools.get_current_week()
            week_examination_num_ = odoo.env['res.archives'].search_count([
                   ('jd_date', '>=', monday),('jd_date', '<=', sunday),
                   #('inspection.log.state', '=', 1)
                ])
            print (week_examination_num_,monday,sunday,datetime.today())
            data_ = {
                'registerNum': register_num_,
                'todayPeopleNum': today_people_num_,
                'todayGhNum': today_gh_num_,
                'weekExaminationNum': week_examination_num_
            }
            return jsonify({'code': 0, 'msg': 'success', 'data': data_, 'success': True})
        except AttributeError as e:
            logging.exception(e)
            return jsonify({'code': 404, 'msg': error_code[404]})
        except Exception as e:
            logging.exception(e)
            return jsonify({'code': 100, 'msg': error_code[100]})

class ArchivesListAPI(Resource):
    """
    查询产妇建档基本信息列表
    :request: post
    :param status: 状态 0管理中 1已结案 查询全部不传
    :param mcyjStart: 末次月经开始时间
    :param mcyjEnd: 末次月经结束时间
    :param gwColorCode: 高危颜色
    :param searchContent: 其他查询-姓名，身份证号，电话,门诊号
    :param isAsc：排序方向
    :param orderByColumn：排序列
    :param pageNum：当前页数
    :param pageSize: 分页大小
    :returns: json string
    """
    #@AppSecurity.public_verify()
    #@AppSecurity.token_verify()
    def post(self):
        try:
            odoo = OdooManager().get_instance()
            params = tools.get_params(request)
            is_asc = params.get('isAsc') if params.get('isAsc', False) else 'asc'
            order_by_column = params.get('orderByColumn') if params.get('orderByColumn', False) else 'create_date'
            #  构造排序方式
            order_ =  order_by_column+' '+ is_asc
            #  初始化页数,返回数据条数,偏移
            page = int(params.get('pageNum')) if params.get('pageNum', False) else 1
            pagesize = int(params.get('pageSize')) if params.get('pageSize', False) else 10
            offset = page * pagesize - pagesize
            #  构造查询条件
            query_ = []
            if params.get('status'): #  状态
                query_.append(('status', '=', int(params.get('status'))))
            if params.get('mcyjStartDate'): # 末次月经开始时间
                query_.append(('mcyjsj', '>=', params.get('mcyjStartDate')))
            if params.get('mcyjEndDate'): # 末次月经结束时间
                query_.append(('mcyjsj', '<=', params.get('mcyjEndDate')))
            if params.get('gwColorCode'): # 高危颜色
                query_.append(('max_gwys', 'in', params.get('gwColorCode')))
            if params.get('searchText'): # 搜索字符串
                query_.append(('mq_xm', 'ilike', int(params.get('searchText'))))  # 孕妇姓名
                query_.append(('mq_sjhm', 'ilike', int(params.get('searchText')))) # 孕妇手机号码
                query_.append(('mq_sfz', 'ilike', int(params.get('searchText')))) # 孕妇身份证号
                query_.append(('mzh', 'ilike', int(params.get('searchText')))) # 冗余门诊号
            fields = [
                    'id','img_url','mq_xm','mq_cz_address','mq_mz','jd_dw',
                    'max_gwys','yz','mq_sfz','sccjrq','jd_date','status', 'danger_color'
                    ]
            total = odoo.env['res.archives'].search_count(query_)
            res_archives = odoo.env['res.archives'].search_read(query_,fields,  offset = offset, limit = pagesize, order = order_)
            data_ = []
            for  res_archives_ in res_archives:
                print(res_archives_)
                data_tmp={
                    'archivesId': res_archives_['id'],
                    'mqXm': res_archives_['mq_xm'],
                    'imgUrl': res_archives_['img_url'],
                    'mqMz': res_archives_['mq_mz'],
                    'mqSfz': res_archives_['mq_sfz'],
                    'mqZz': res_archives_['mq_cz_address'],
                    'sccjsj': res_archives_['sccjrq'],
                    'yz': tools.parase_yz(1, res_archives_['yz']),
                    'gwColorCode': res_archives_['danger_color'],
                    'jdJg': res_archives_['jd_dw'][1] if res_archives_['jd_dw'] else '',
                    'jdDate': res_archives_['jd_date'],
                    'status': res_archives_['status'] or 0
                }
                data_.append(data_tmp)
            return jsonify({'code': 0, 'msg': 'success', 'data': data_, 'total': total , 'success': True})
        except AttributeError as e:
            logging.exception(e)
            return jsonify({'code': 404, 'msg': error_code[404]})
        except Exception as e:
            logging.exception(e)
            return jsonify({'code': 100, 'msg': error_code[100]})

class  ArchivesSelectByArchivesIdAPI(Resource):
    """
    档案详情根据档案号查询信息
    :request: get
    :param archivesId：档案ID
    :returns: json string
    """
    def get(self):
        try:
            odoo = OdooManager().get_instance()
            #  参数校验
            params = request.values
            req_params = ['archivesId']
            vrf_res = tools.required_parame_verif(req_params,params)
            if  vrf_res['code'] != 0:
                return jsonify(vrf_res)
            query_ = [('id', '=', int(params.get('archivesId')))]
            data_ = {
                # 产前筛查对象
                'cqsc': None,
                # 艾梅乙筛查对象
                'amebTestVo': None,
                # 高危妊娠筛查对象
                'gwrssc': None,
                # 高危评分对象
                'gwpf': None
            }
            # 获取当前档案信息
            res_archives = odoo.env['res.archives'].search_read(query_)
            res_archives_item = res_archives[0]
            if (not res_archives_item):
                return jsonify({
                    'code': 1,
                    'msg': "用户不存在"
                })
            #  查询产前筛查对象
            inspection_tang_case = odoo.env['inspection.tang.case'].search_read([('archives_id', '=', int(params.get('archivesId')))])
            if inspection_tang_case:
                inspection_tang_case_ = inspection_tang_case.pop()
                data_['cqsc'] = {
                    'st18Jcjg': '',
                    'st21Jcjg': '',
                    'ntdJcjg': '',
                    'cqscYz': ''#inspection_tang_case_['jbxx_csyz']
                }
                st18 = inspection_tang_case_['st18_jcjg']
                st21 = inspection_tang_case_['st21_jcjg']
                ntd = inspection_tang_case_['ntd_mom']
                if st18 and st18.find('/') != -1:
                    st18Arr = st18.split('/')
                    if int(st18Arr[1]) > 360 and int(st18Arr[1]) < 1000:
                        data_['cqsc']['st18Jcjg'] = '临界风险'
                    elif int(st18Arr[1]) < 360:
                        data_['cqsc']['st18Jcjg'] = '高风险'
                    elif int(st18Arr[1]) > 1000:
                        data_['cqsc']['st18Jcjg'] = '低风险'
                if st21 and st21.find('/') != -1:
                    st21Arr = st21.split('/')
                    if int(st21Arr[1]) > 270 and int(st21Arr[1]) < 1000:
                        data_['cqsc']['st21Jcjg'] = '临界风险'
                    elif int(st21Arr[1]) < 270:
                        data_['cqsc']['st21Jcjg'] = '高风险'
                    elif int(st21Arr[1]) > 1000:
                        data_['cqsc']['st21Jcjg'] = '低风险'
                if ntd:
                    if int(ntd) > 2.5:
                        data_['cqsc']['ntdJcjg'] = '高风险'
                    else:
                        data_['cqsc']['ntdJcjg'] = '低风险'
                start = res_archives_item['mcyjsj']
                end = inspection_tang_case_['jbxx_djrq']
                if end and start:
                    data_['cqsc']['cqscYz'] = tools.parase_yz(1, tools.diff_date_count(start, end[0:10]))
            #  查询艾梅乙筛查对象
            inspection_amy = odoo.env['inspection.amy'].search_read([('archives_id', '=', int(params.get('archivesId')))])
            if inspection_amy:
                inspection_amy_ = inspection_amy.pop()
                data_['amebTestVo'] = {
                    'mdJcjg': '阴性' if inspection_amy_['md_jcjg'] == '0' else '阳性',
                    'hivJcjg': '阴性' if inspection_amy_['hiv_jcjg'] == '0' else '阳性',
                    'ygJcjg': '阴性' if inspection_amy_['yg_jcjg'] == '0' else '阳性',
                    'ameYz': ''#inspection_amy_['yg_jcjg']
                }
                start = res_archives_item['mcyjsj']
                end = inspection_amy_['register_date']
                if start and end:
                    data_['amebTestVo']['ameYz'] = tools.parase_yz(1, tools.diff_date_count(start, end[0:10]))
            #  更新高危妊娠筛查对象
            if res_archives_item['gwys_ids']:
                #  查询高危妊娠筛查对象、高危评分对象
                data_['gwrssc'] = {
                    'gwrsscYz': '',
                    'gwysList': []
                }
                # 查询最新的诊断处理记录
                zd_info = odoo.env['inspection.diagnostic'].search_read([('archives_id', '=', int(params.get('archivesId'))), ('inspection_log_id', '!=', None)])
                if zd_info:
                    zd_info = zd_info.pop()
                start = res_archives_item['mcyjsj']
                end = zd_info['cl_zdsj']
                if start and end:
                    data_['gwrssc']['gwrsscYz'] = tools.parase_yz(1, tools.diff_date_count(start, end[0:10]))
                dict_gwys = odoo.env['dict.gwys'].search_read([('id', 'in', res_archives_item['gwys_ids'])])
                for gwys in dict_gwys:
                    gwys_data={
                        'gwysBm': gwys['code'],
                        'gwysMc': gwys['name'],
                        'gwColorCode': gwys['color']
                    }
                    data_['gwrssc']['gwysList'].append(gwys_data)
            #  更新高危评分对象
            if res_archives_item['gwpf_ids']:
                gwpf = odoo.env['risk.score.record'].search_read([('archives_id', '=', int(params.get('archivesId')))])
                if gwpf:
                    gwpf = gwpf.pop()
                data_['gwpf'] = {
                    'gwColorCode': res_archives_item['danger_color'],
                    'gwpf': gwpf['total']
                }
            print(res_archives_item)
            return jsonify({'code': 0, 'msg': 'success', 'data': data_, 'success': True})
        except AttributeError as e:
            logging.exception(e)
            return jsonify({'code': 404, 'msg': error_code[404]})
        except Exception as e:
            logging.exception(e)
            return jsonify({'code': 100, 'msg': error_code[100]})

class ArchivesGetOutpatientStepAPI(Resource):
    """
    查询档案信息及进度步骤-门诊及住院 绑定信息
    :request: get
    :param archivesId：档案ID
    :returns: json string
    """
    def get(self):
        try:

            odoo = OdooManager().get_instance()
            #  参数校验
            params = request.values
            req_params = ['archivesId']
            vrf_res = tools.required_parame_verif(req_params,params)
            if  vrf_res['code'] != 0:
                return jsonify(vrf_res)
            query_ = [('id', '=', int(params.get('archivesId')))]
            res_archives = odoo.env['res.archives'].search_read(query_)
            data_ = {}
            hospital_id = 0
            if res_archives:
                res_archive_ = res_archives[0]
                data_ = {
                    'mqXm': res_archive_['mq_xm'],
                    'mqAge': tools.calculate_age_by_card(res_archive_['mq_sfz']),
                    'mqMz': res_archive_['mq_mz'],
                    'yz': res_archive_['yz'],
                    'yc': 0,
                    'cc': 0,
                    'mzh': res_archive_['mzh'],
                    'mcyj': res_archive_['mcyjsj'],
                    'gwys': res_archive_['gwys_ids'],
                    'gwColor': dict_handler.get_dict_value(res_archive_['danger_color'],'ck_gwys'), # 高危颜色,
                    'gwColorCode': res_archive_['danger_color'],
                    'step': {'yfjd': 1,'yqcj': 0,'cgcj': 0,'cqsc': 0,'ch42': 0,'fmjl': 0}, # 步骤:孕妇建档,孕期初检,常规产检,产前筛查,产后42天,分娩记录
                    'logIds': [],
                    'hospitalization': {
                        'zyh': res_archive_['zyh'],
                        'bed': res_archive_['bed'],
                        'departmentName': res_archive_['ks'],
                        'hlDj': res_archive_['hl_dj'],
                    }
                }
                # 更新高危因素
                if res_archive_['gwys_ids']:
                    gwys_list = odoo.env['dict.gwys'].search_read([('id', 'in', res_archive_['gwys_ids'])],
                                                                  ['name', 'code', 'id'])
                    data_['gwys'] = gwys_list
                hospital_id = res_archive_['hospital_id']
            #  更新步骤
            inspection_log_ = odoo.env['inspection.log'].search_read([('archives_id', '=', int(params.get('archivesId'))), ('state', 'in', ['0', '1'])])
            if inspection_log_:
                for log_ in inspection_log_:
                    if log_['type'] == '1':
                        data_['step']['yqcj'] = 1
                    elif  log_['type'] == '2':
                        data_['step']['cgcj'] = 1
                    elif  log_['type'] == '3':
                        data_['step']['ch42'] = 1
            birth_record_ = odoo.env['birth.record'].search_read(query_)
            if birth_record_:
                data_['step']['fmjl'] = 1
            inspection_tang_case_ = odoo.env['inspection.tang.case'].search_read(query_)
            if inspection_tang_case_:
                data_['step']['cqsc'] = 1
            #  查询检查日志表集合
            inspection_log = odoo.env['inspection.log'].search_read([('archives_id', '=', int(params.get('archivesId'))), ('state', 'in', ['0', '1'])])
            if inspection_log:
                for inspection_log_ in inspection_log:
                    log_tmp = {
                        'logid': inspection_log_['id'],
                        'type': inspection_log_['type'],
                        'dataSource': hospital_id,
                        'state': inspection_log_['state']
                    }
                    data_['logIds'].append(log_tmp)
            return jsonify({'code': 0, 'msg': 'success', 'data': data_, 'success': True})
        except AttributeError as e:
            logging.exception(e)
            return jsonify({'code': 404, 'msg': error_code[404]})
        except Exception as e:
            logging.exception(e)
            return jsonify({'code': 100, 'msg': error_code[100]})

class ArchivesGetCheckListAPI(Resource):
    """
    档案详情获取检查列表
    :request: post
    :param archivesId：档案ID
    :param checkType：检查类型 不传 全部 1:孕期初检;2:常规检查;3:产后42天检查 4 产前筛查与诊断-唐筛-早唐 5 产前筛查与诊断-NT 6 分娩 7 产后42天检查问询
    :param isAsc：排序方向
    :param orderByColumn：排序列
    :param pageNum：当前页数
    :param pageSize: 分页大小
    :returns: json string
    """
    #@AppSecurity.public_verify()
    #@AppSecurity.token_verify()
    def post(self):
        try:
            odoo = OdooManager().get_instance()
            params = tools.get_params(request)
            is_asc = params.get('isAsc') if params.get('isAsc', False) else 'asc'
            order_by_column = params.get('orderByColumn') if params.get('orderByColumn', False) else 'create_date'
            #  构造排序方式
            order_ =  order_by_column+' '+ is_asc
            #  初始化页数,返回数据条数,偏移
            page = int(params.get('pageNum')) if params.get('pageNum', False) else 1
            pagesize = int(params.get('pageSize')) if params.get('pageSize', False) else 10
            offset = page * pagesize - pagesize
            query_params = [
                ('archives_id', '=', int(params.get('archivesId'))),
                ('state', '=', '1')
            ]
            if (params.get('checkType')):
                query_params.append(('type', '=', params.get('checkType')))
            res = odoo.env['inspection.log'].search_read(query_params, offset = offset, limit = pagesize, order = order_)
            total = odoo.env['inspection.log'].search_count(query_params)
            rows = []
            if (res and len(res) != 0):
                for res_item in res:
                    # 获取档案信息
                    archives_info = odoo.env['res.archives'].search_read([('id', '=', res_item['archives_id'][0])])[0]
                    # 诊断处理信息
                    zd_info = None
                    if res_item['zdcl_id'] and res_item['zdcl_id'][0]:
                        zd_info = odoo.env['inspection.diagnostic'].search_read([('id', '=', res_item['zdcl_id'][0])])[0]
                    # 体格检查信息
                    physical_info = None
                    # 胎儿信息
                    te_info = None
                    if res_item['tgjx_id'] and res_item['tgjx_id'][0]:
                        physical_info = odoo.env['inspection.physical'].search_read([('id', '=', res_item['tgjx_id'][0])])[0]
                        te_info_list = odoo.env['inspection.physical.fetus'].search_read([('pid', '=', res_item['tgjx_id'][0])])
                        if te_info_list:
                            te_info = te_info_list[0]
                    # 实验室
                    sys_info = None
                    if res_item['sys_id'] and res_item['sys_id'][0]:
                        sys_info = odoo.env['inspection.laboratory'].search_read([('id', '=', res_item['sys_id'][0])])[0]
                    row_item = {
                        'checkId': res_item['id'],
                        'archivesId': res_item['archives_id'][0],
                        'checkType': res_item['type'],
                        'checkDate': res_item['create_date'],
                        'yz': tools.parase_yz(1, tools.diff_date_count(archives_info['mcyjsj'], zd_info['cl_zdsj'][0:10])),
                        'jjYs': zd_info['cl_ys_id'][1] if zd_info and zd_info['cl_ys_id'] else None,
                        # 诊断 数据来源zd_info
                        'jjJg': zd_info['hospital_id'][1] if zd_info and zd_info['hospital_id'] else None,
                        'gwpf': '',
                        # archives_info
                        'gwys': archives_info['gwys_ids'] if archives_info else None,
                        # 诊断 高危颜色
                        'gwColor': zd_info['gwpg_gwys'] if zd_info['gwpg_gwys'] else None,
                        'gwColorCode': zd_info['gwpg_gwys'] if zd_info['gwpg_gwys'] else None,
                        'checkData': {
                            'tz': physical_info['cg_tz'] if physical_info else None,
                            'xySsy': physical_info['cg_ssy'] if physical_info else None,
                            'xySzy': physical_info['cg_szy'] if physical_info else None,
                            'gg': physical_info['cg_gg'] if physical_info else None,
                            'fw': physical_info['cg_fw'] if physical_info else None,
                            'xj': physical_info['cg_xj'] if physical_info else None,
                            'fz': physical_info['cg_fz'] if physical_info else None,
                            'tw': te_info['tejc_tw'] if te_info else None,
                            'ndb': sys_info['ncg_ndb'] if sys_info else None,
                            'td': te_info['tejc_td'] if te_info else None,
                            'tx': te_info['tejc_xl'] if te_info else None,
                        }
                    }
                    # 更新高危因素
                    if zd_info['gwsc_gwfx']:
                        gwsc_gwfx = json.loads(zd_info['gwsc_gwfx'])
                        arr = []
                        for item in gwsc_gwfx:
                            arr.append({
                                "name": item['gwysMc'],
                                "code": item['gwysCode'],
                                "color": item['gwysColor']
                            })
                        row_item['gwys'] = arr
                    rows.append(row_item)
            return jsonify({
                'code': 0,
                'msg': 'success',
                'data': {
                    'rows': rows,
                    'total': total
                },
                'success': True
            })
        except AttributeError as e:
            logging.exception(e)
            return jsonify({'code': 404, 'msg': error_code[404]})
        except Exception as e:
            logging.exception(e)
            return jsonify({'code': 100, 'msg': error_code[100]})

class ArchivesGetFenMianCenterDataAPI(Resource):
    """
    获取云平台分娩记录格式数据
    :request: get
    :param archivesId：档案ID
    :returns: json string
    """
    def get(self):
        try:
            odoo = OdooManager().get_instance()
            #  参数校验
            params = request.values
            req_params = ['archivesId']
            vrf_res = tools.required_parame_verif(req_params,params)
            if  vrf_res['code'] != 0:
                return jsonify(vrf_res)
            query_ = [('archives_id', '=', int(params.get('archivesId')))]
            data_ = {}
            birth_record_cloud = odoo.env['birth.record.cloud'].search_read(query_)
            if birth_record_cloud:
                birth_record_cloud_ = birth_record_cloud[0]
                data_ = {
                    'cfqk': {
                        'cfMqXm': birth_record_cloud_['cf_mq_xm'],
                        'cfSfz': birth_record_cloud_['cf_sfz'],
                        'cfJsdw': birth_record_cloud_['cf_jsdw'],
                        'cfMcyj': birth_record_cloud_['cf_mcyj'],
                        'cfFmdd': birth_record_cloud_['cf_fmdd'],
                        'cfZyh': birth_record_cloud_['cf_zyh'],
                        'cfZysj': birth_record_cloud_['cf_zysj'],
                        'cfCysj': birth_record_cloud_['cf_cysj'],
                        'cfJsr': birth_record_cloud_['cf_jsr'],
                        'cfSfZwyf': birth_record_cloud_['cf_sf_zwyf'],
                        'cfYzZ': birth_record_cloud_['cf_yz_z'],
                        'cfYzT': birth_record_cloud_['cf_yz_t'],
                        'cfFmsj': birth_record_cloud_['cf_fmsjs']
                    },
                    'fmxx': {
                        'cfFmyc': birth_record_cloud_['cf_fmyc'],
                        'cfCb': birth_record_cloud_['cf_cb'],
                        'cfFmfs': birth_record_cloud_['cf_fmfs'],
                        'cfXySs': birth_record_cloud_['cf_xy_ss'],
                        'cfXySz': birth_record_cloud_['cf_xy_sz'],
                        'cfZcc': birth_record_cloud_['cf_zcc'],
                        'cfDycc': birth_record_cloud_['cf_dycc'],
                        'cfDecc': birth_record_cloud_['cf_decc'],
                        'cfDscc': birth_record_cloud_['cf_dscc'],
                        'cfYsl': birth_record_cloud_['cf_ysl'],
                        'cfYss': birth_record_cloud_['cf_yss'],
                        'cfChcx': birth_record_cloud_['cf_chcx'],
                        'cfChcxyy': birth_record_cloud_['cf_chcxyy'],
                        'cfChcx2h': birth_record_cloud_['cf_chcx2h'],
                        'cfChcx24h': birth_record_cloud_['cf_chcx24h'],
                        'cfCxl': birth_record_cloud_['cf_cxl'],
                        'cfYwsx': birth_record_cloud_['cf_ywsx'],
                        'cfHivZx': birth_record_cloud_['cf_hiv_zx'],
                        'cfHivJg': birth_record_cloud_['cf_hiv_jg'],
                        'cfMdJg': birth_record_cloud_['cf_md_jg'],
                        'cfYgJg': birth_record_cloud_['cf_yg_jg'],
                        'cfMdRpr': birth_record_cloud_['cf_md_rpr'],
                        'cfYeMdRpr': birth_record_cloud_['cf_ye_md_rpr'],
                        'cfRgpm': birth_record_cloud_['cf_rgpm'],
                        'cfCcs': birth_record_cloud_['cf_ccs'],
                        'cfRgbl': birth_record_cloud_['cf_rgbl'],
                        'cfTxl': birth_record_cloud_['cf_txl'],
                        'cfYfsw': birth_record_cloud_['cf_yfsw'],
                        'wzycf': birth_record_cloud_['cf_zwyf'],
                        'cfYfswYy': birth_record_cloud_['cf_yfsw_yy'],
                        'cfBfzSelect': birth_record_cloud_['cf_bfz_select'],
                        'cfBfz': birth_record_cloud_['cf_bfz'],
                        'cfRcgxySelect': birth_record_cloud_['cf_rcgxy_select'],
                        'cfHbz': birth_record_cloud_['cf_hbz'],
                        'cfHbzQt': birth_record_cloud_['cf_hbz_qt'],
                        'cfYlcs': birth_record_cloud_['cf_ylcs'],
                        'cfYcsm': birth_record_cloud_['cf_ycsm']
                    },
                    'sjjgCode': birth_record_cloud_['sjjg'],
                    'teqk': [],
                    'sjjg': birth_record_cloud_['sjjg'],
                    'sjsj': birth_record_cloud_['sjsj']
                }
                #  获取新生儿记录信息
                query_ = [('main_id', '=', birth_record_cloud_['id'])]
                birth_record_cloud_line = odoo.env['birth.record.cloud.line'].search_read(query_)
                if birth_record_cloud_line:
                    for line_ in birth_record_cloud_line:
                        xer_ = {
                           'id': line_['id'],
                           'teMcsj': line_['te_mcsj'],
                           'teXb': line_['te_xb'],
                           'teTz': line_['te_tz'],
                           'teSc': line_['te_sc'],
                           'teZm': line_['te_zm'],
                           'teGj': line_['te_gj'],
                           'teApgar1': line_['te_apgar1'],
                           'teApgar5': line_['te_apgar5'],
                           'teApgar10': line_['te_apgar10'],
                           'teSw': line_['te_sw'],
                           'teMyqdb': line_['te_myqdb'],
                           'teSfwz': line_['te_sfwz'],
                           'teWzcl': line_['te_wzcl'],
                           'teSfjx': line_['te_sfjx'],
                           'teJxYy': line_['te_jx_yy'],
                           'teJxqt': line_['te_jxqt'],
                           'teSfhb': line_['te_sfhb'],
                           'teHbYy': line_['te_hb_yy'],
                           'teHbqt': line_['te_hbqt'],
                           'teCsjj': line_['te_csjj'],
                           'teSwsj': line_['te_swsj'],
                           'teSwyy': line_['te_swyy'],
                           'teCsqx': line_['te_csqx']
                        }
                        data_['teqk'].append(xer_)
            return jsonify({'code': 0, 'msg': 'success', 'data': data_, 'success': True})
        except AttributeError as e:
            logging.exception(e)
            return jsonify({'code': 404, 'msg': error_code[404]})
        except Exception as e:
            logging.exception(e)
            return jsonify({'code': 100, 'msg': error_code[100]})

class ArchivesGetUteHeiCurAPI(Resource):
    """
    查询宫高体重曲线图
    :request: get
    :param archivesId：档案ID
    :param type：类型 0-宫高 1-体重
    :returns: json string
    """
    def get(self):
        try:
            odoo = OdooManager().get_instance()
            #  参数校验
            params = request.values
            req_params = ['archivesId','type']
            vrf_res = tools.required_parame_verif(req_params,params)
            if  vrf_res['code'] != 0:
                return jsonify(vrf_res)
            data = {'max':[],'min':[],'data':[],'headers':[]}
            #初始孕周
            init_yz = 0
            init_date = ''
            query_ = [('id', '=', int(params.get('archivesId')))]
            res_archives = odoo.env['res.archives'].search_read(query_,['yz','jd_date'])
            if  res_archives:
                init_yz =  res_archives[0]['yz']
                init_date =  res_archives[0]['jd_date']
            #宫高
            if params.get('type')==0:
                query_ = [('archives_id', '=', int(params.get('archivesId')))]
                order_ = 'cg_tjrq asc'
                physical = odoo.env['inspection.physical'].search_read(query_,['cg_gg','cg_tjrq'],order = order_)
                if physical:
                    for  physical_ in physical:
                        now_yz=tools.diff_datetime_yz(init_date,physical_['cg_tjrq'],init_yz)
                        now_cg_gg=physical_['cg_gg']
                        if now_yz>=20 and now_yz<=40:
                            data['data'].append(now_cg_gg)
                            data['headers'].append(now_yz)
                            data['min'].append(now_cg_gg*1.1)
                            data['max'].append(now_cg_gg*0.9)
            #体重
            else:
                query_ = [('archives_id', '=', int(params.get('archivesId')))]
                order_ = 'cg_tjrq asc'
                physical = odoo.env['inspection.physical'].search_read(query_,['cg_tz','cg_tjrq'],order = order_)
                if physical:
                    for  physical_ in physical:
                        now_yz=tools.diff_datetime_yz(init_date,physical_['cg_tjrq'],init_yz)
                        now_cg_tz=physical_['cg_tz']
                        data['data'].append(now_cg_tz)
                        data['headers'].append(now_yz)
                        data['min'].append(now_cg_tz*1.1)
                        data['max'].append(now_cg_tz*0.9)
            return jsonify({'code': 0, 'msg': 'success', 'data': data})
        except AttributeError as e:
            logging.exception(e)
            return jsonify({'code': 404, 'msg': error_code[404]})
        except Exception as e:
            logging.exception(e)
            return jsonify({'code': 100, 'msg': error_code[100]})

class ArchivesGetFollowUpRecordListAPI(Resource):
    """
    查询档案详情随访任务列表
    :request: post
    :param archivesId：档案ID
    :param isAsc：排序方向
    :param orderByColumn：排序列
    :param pageNum：当前页数
    :param pageSize: 分页大小
    :returns: json string
    """
    #@AppSecurity.public_verify()
    #@AppSecurity.token_verify()
    def post(self):
        try:
            odoo = OdooManager().get_instance()
            params = tools.get_params(request)
            req_params = ['archivesId']
            vrf_res = tools.required_parame_verif(req_params,params)
            if  vrf_res['code'] != 0:
                return jsonify(vrf_res)
            is_asc = params.get('isAsc') if params.get('isAsc', False) else 'asc'
            order_by_column = params.get('orderByColumn') if params.get('orderByColumn', False) else 'create_date'
            #  构造排序方式
            order_ =  order_by_column+' '+ is_asc
            #  初始化页数,返回数据条数,偏移
            print (params.get('pageNum', False))
            page = int(params.get('pageNum')) if params.get('pageNum', False) else 1
            pagesize = int(params.get('pageSize')) if params.get('pageSize', False) else 10
            offset = page * pagesize - pagesize
            #  构造查询条件
            query_ = [('archives_id', '=', int(params.get('archivesId')))]
            fields = [
                    'id','state','name','follow_data_type','start_time','follow_yz',
                    'follow_type','hospital_id','end_time','user_id'
                ]
            inspection_follow_recall = odoo.env['inspection.follow.recall'].search_read(query_,fields,  offset = offset, limit = pagesize, order = order_)
            data_ = []
            if inspection_follow_recall:
                for  recall_ in inspection_follow_recall:
                    data_tmp={
                        'id': recall_['id'],
                        'status': recall_['state'],
                        'sfRwBh': recall_['name'],
                        'sfRwLx': recall_['follow_data_type'],
                        'jdFqSj': recall_['start_time'],
                        'sfRwYz': recall_['follow_yz'],
                        'sfRwFs': recall_['follow_type'],
                        'sfJg': recall_['hospital_id'][1] if recall_['hospital_id'] else '',
                        'jdWcSj': recall_['end_time'],
                        'sfrCode': recall_['user_id'][0] if recall_['user_id'] else '',
                        'sfrName': recall_['user_id'][1] if recall_['user_id'] else ''
                    }
                    data_.append(data_tmp)
            total_ = odoo.env['inspection.follow.recall'].search_count(query_)
            return jsonify({'code': 0, 'msg': 'success', 'data': data_, 'success': True})
        except AttributeError as e:
            logging.exception(e)
            return jsonify({'code': 404, 'msg': error_code[404]})
        except Exception as e:
            logging.exception(e)
            return jsonify({'code': 100, 'msg': error_code[100]})

class ArchivesGetOutPatientAPI(Resource):
    """
    获取HIS中患者基本信息-根据身份证查询
    :request: post
    :param idCardType：证件类别
    :param idNo：证件号码
    :returns: json string
    """
    def post(self):
        try:
            odoo = OdooManager().get_instance()
            params = tools.get_params(request)
            req_params = ['idCardType','idNo']
            vrf_res = tools.required_parame_verif(req_params,params)
            if  vrf_res['code'] != 0:
                return jsonify(vrf_res)
            his_ = his_api.APIHis()
            idCardType=params.get('idCardType')
            idNo=params.get('idNo')
            data_ = {}
            records_list = his_.get_pacs_web_report(idCardType=idCardType,idNo=idNo)
            if records_list:
                record_=records_list[0]
                data_ = {
                    'aboType': record_['aboType'],
                    'name': record_['name'],
                    'sex': record_['sex'],
                    'nation': record_['nation'],
                    'address': record_['address'],
                    'tel': '',
                    'cardNo': record_['cardNo'],
                    'cureDeptCode': record_['cureDept'],
                    'cureDeptName': '',
                    'jdStatus': '',
                    'nullahNumber': record_['nullahNumber'],
                    'nullahDate': record_['registerDate'],
                    'state': ''
                }
                #  更新档案信息
                query_ = [('mq_sfz', '=', params.get('idNo'))]
                res_archive = odoo.env['res.archives'].search_read(query_,['id','status','mq_sjhm'])
                if res_archive:
                    res_archive = res_archive[0]
                    data_['jdStatus'] = res_archive['status']
                    data_['tel'] = res_archive['mq_sjhm']
                #  1000:候诊 1001:在诊 9999:已诊
                if record_['state'] == '1000':
                    data_['state'] = '候诊'
                elif record_['state'] == '1001':
                    data_['state'] = '在诊'
                else:
                    data_['state'] = '已诊'
            return jsonify({'code': 0, 'msg': 'success', 'data': data_, 'success': True})
        except AttributeError as e:
            logging.exception(e)
            return jsonify({'code': 404, 'msg': error_code[404]})
        except Exception as e:
            logging.exception(e)
            return jsonify({'code': 100, 'msg': error_code[100]})
